<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地址管理</title>
    <!-- 引入Vue -->
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- Axios for HTTP requests -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- 引入Element UI -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入Font Awesome图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <!-- 引入自定义样式 -->
    <link rel="stylesheet" href="css/location.css">
</head>
<body>
<div id="app" class="container">
    <!-- 导航栏 -->
    <nav class="navbar">
        <a href="/index.html" class="navbar-brand">
            🐛 小蚕活动平台
        </a>
        <div class="navbar-nav">
            <a href="/index.html" class="nav-link">
                🏠 首页
            </a>
            <a href="#" class="nav-link active">
                📍 地址管理
            </a>
            <a href="/notify.html" class="nav-link">
                🔔 通知管理
            </a>
        </div>
    </nav>
    <!-- 地址列表区域 -->
    <el-card v-if="!isAdding && !isEditing" class="mt-4" style="border-radius: 12px; border: none; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);" v-loading="loading">
        <div slot="header" class="card-header">
            <span>已保存的地址</span>
            <el-button class="add-address-btn" @click="startAddAddress" :disabled="loading" style="display: flex; align-items: center; gap: 5px;">
                <i class="fa fa-plus"></i> 新增地址
            </el-button>
        </div>

        <div v-if="addressList.length === 0" class="empty-state">
            <el-empty description="暂无保存的地址">
                <el-button class="add-address-btn" @click="startAddAddress" slot="bottom">
                    <i class="fa fa-plus"></i> 新增第一个地址
                </el-button>
            </el-empty>
        </div>

        <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
            <el-card
                    v-for="(address, index) in addressList"
                    :key="address.id"
                    class="address-card"
                    :style="{animationDelay: (index * 0.1) + 's'}"
            >
                <div>
                    <div class="address-header">
                        <div class="address-name">
                            <i class="fa fa-map-marker"></i> {{ address.name }}
                        </div>
                    </div>

                    <p class="address-main">{{ address.address }}</p>

                    <div class="operation-buttons">
                        <el-button
                                size="small"
                                class="edit-btn"
                                @click="startEditAddress(address)"
                                :disabled="loading"
                                style="display: flex; align-items: center; gap: 3px;"
                        >
                            <i class="fa fa-pencil"></i> 编辑
                        </el-button>
                        <el-button
                                size="small"
                                class="delete-btn"
                                @click="deleteAddress(address.id, index)"
                                :disabled="loading"
                                style="display: flex; align-items: center; gap: 3px;"
                        >
                            <i class="fa fa-trash"></i> 删除
                        </el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </el-card>

    <!-- 新增地址表单 -->
    <el-card v-if="isAdding" class="mt-4" style="border-radius: 12px; border: none; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);">
        <div slot="header" class="card-header">
            <span>新增地址</span>
            <el-button type="text" @click="cancelOperation" style="display: flex; align-items: center; gap: 3px;">
                <i class="fa fa-times"></i> 取消
            </el-button>
        </div>

        <el-form
                :model="form"
                ref="form"
                :rules="rules"
                label-width="100px"
                class="mt-4"
        >
            <!-- 地区选择 -->
            <el-form-item
                    label="所在地区"
                    prop="region"
            >
                <el-cascader
                        v-model="form.region"
                        :options="regionOptions"
                        :props="regionProps"
                        clearable
                        placeholder="请选择省/市/区"
                        @change="handleRegionChange"
                        style="width: 100%;"
                ></el-cascader>
            </el-form-item>

            <!-- 地址搜索 -->
            <el-form-item
                    label="详细地址"
                    prop="selectedAddress"
                    v-if="form.cityCode"
            >
                <el-autocomplete
                        v-model="form.addressKeyword"
                        :fetch-suggestions="queryAddress"
                        placeholder="请输入详细地址"
                        @select="handleAddressSelect"
                        value-key="value"
                        clearable
                        style="width: 100%;"
                >
                    <template slot-scope="{ item }">
                        <div style="line-height: 1.5;">
                            <div style="font-weight: 500; color: #333;">{{ item.title }}</div>
                            <div style="font-size: 12px; color: #666; margin-top: 2px;">{{ item.address }}</div>
                        </div>
                    </template>
                </el-autocomplete>

                <!-- 选中的地址信息 -->
                <div v-if="form.selectedAddress" class="selected-address">
                    <p class="title">{{ form.selectedAddress.title }}</p>
                    <p class="detail">{{ form.selectedAddress.address }}</p>
                </div>
            </el-form-item>

            <!-- 推送SPT -->
            <el-form-item
                    label="推送SPT"
                    prop="spt"
            >
                <el-input
                        v-model="form.spt"
                        placeholder="请输入推送SPT内容（选填）"
                        maxlength="100"
                ></el-input>
            </el-form-item>

            <!-- 推送开关 -->
            <el-form-item label="是否推送">
                <el-switch
                        v-model="form.pushSwitch"
                        active-text="是"
                        inactive-text="否"
                        active-color="#36b37e"
                ></el-switch>
            </el-form-item>

            <!-- 按钮区域 -->
            <div class="form-actions">
                <el-button @click="cancelOperation" :disabled="loading">取消</el-button>
                <el-button type="primary" @click="submitForm" :loading="loading" style="display: flex; align-items: center; gap: 5px;">
                    <i class="fa fa-check"></i> 确定
                </el-button>
            </div>
        </el-form>
    </el-card>

    <!-- 编辑地址表单 -->
    <el-card v-if="isEditing" class="mt-4" style="border-radius: 12px; border: none; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);">
        <div slot="header" class="card-header">
            <span>编辑地址</span>
            <el-button type="text" @click="cancelOperation" style="display: flex; align-items: center; gap: 3px;">
                <i class="fa fa-times"></i> 取消
            </el-button>
        </div>

        <el-form
                :model="form"
                ref="form"
                label-width="100px"
                class="mt-4"
        >
            <!-- 地址信息（不可编辑） -->
            <el-form-item label="地址名称">
                <el-input v-model="form.name" disabled></el-input>
            </el-form-item>

            <el-form-item label="详细地址">
                <el-input v-model="form.address" disabled type="textarea" :rows="2"></el-input>
            </el-form-item>

            <!-- 可编辑的内容 -->
            <el-form-item
                    label="推送SPT"
                    prop="spt"
            >
                <el-input
                        v-model="form.spt"
                        placeholder="请输入推送SPT内容（选填）"
                        maxlength="100"
                ></el-input>
            </el-form-item>

            <el-form-item label="是否推送">
                <el-switch
                        v-model="form.pushSwitch"
                        active-text="是"
                        inactive-text="否"
                        active-color="#36b37e"
                ></el-switch>
            </el-form-item>

            <!-- 按钮区域 -->
            <div class="form-actions">
                <el-button @click="cancelOperation" :disabled="loading">取消</el-button>
                <el-button type="primary" @click="updateForm" :loading="loading" style="display: flex; align-items: center; gap: 5px;">
                    <i class="fa fa-check"></i> 保存
                </el-button>
            </div>
        </el-form>
    </el-card>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                // 地址列表
                addressList: [],

                // 地区数据
                regionOptions: [],

                // 级联选择器配置
                regionProps: {
                    value: 'code',
                    label: 'name',
                    children: 'child'
                },

                // 表单数据
                form: {
                    id: null,
                    name: '',
                    address: '',
                    region: [], // 存储地区选择的code数组
                    cityCode: null, // 最后一级地区的code (Integer类型)
                    addressKeyword: '', // 地址搜索关键词
                    selectedAddress: null, // 选中的地址信息
                    spt: '', // 推送SPT内容
                    pushSwitch: false // 是否推送
                },

                // 表单验证规则
                rules: {
                    region: [
                        { required: true, message: '请选择所在地区', trigger: 'change' }
                    ],
                    selectedAddress: [
                        { required: true, message: '请选择详细地址', trigger: 'change' }
                    ],
                },

                // 状态控制
                isAdding: false,
                isEditing: false,
                loading: false
            };
        },
        mounted() {
            this.loadAddressList();
            this.loadRegionOptions();
        },
        methods: {
            // 加载地址列表
            async loadAddressList() {
                this.loading = true;
                try {
                    const response = await axios.get('/api/location');
                    if (response.data.success) {
                        this.addressList = response.data.data || [];
                    } else {
                        this.$message.error(response.data.msg || '获取地址列表失败');
                    }
                } catch (error) {
                    console.error('获取地址列表失败:', error);
                    this.$message.error('获取地址列表失败，请检查网络连接');
                } finally {
                    this.loading = false;
                }
            },
            
            // 加载地区选项数据
            async loadRegionOptions() {
                try {
                    const response = await axios.get('/api/location/cityCode');
                    if (response.data.success) {
                        this.regionOptions = response.data.data || [];
                    } else {
                        console.error('获取地区数据失败:', response.data.msg);
                        this.$message.error('获取地区数据失败');
                    }
                } catch (error) {
                    console.error('获取地区数据失败:', error);
                    this.$message.error('获取地区数据失败，请检查网络连接');
                }
            },
            // 返回按钮处理
            handleBack() {
                window.location.href = '/index.html';
            },

            // 开始新增地址
            startAddAddress() {
                this.isAdding = true;
                this.isEditing = false;
                this.resetForm();
            },

            // 开始编辑地址
            startEditAddress(address) {
                this.isEditing = true;
                this.isAdding = false;

                // 填充表单数据（仅可编辑spt和pushSwitch）
                this.form = {
                    id: address.id,
                    name: address.name,
                    address: address.address,
                    spt: address.spt || '',
                    pushSwitch: address.pushSwitch,
                    region: [],
                    cityCode: address.cityCode,
                    addressKeyword: '',
                    selectedAddress: null
                };
            },
        // 查询地址（调用真实接口）
        async queryAddress(queryString, callback) {
          if (!this.form.cityCode || !queryString.trim()) {
            callback([]);
            return;
          }
          
          try {
            // 调用真实的地址搜索接口
            const response = await axios.get('/api/location/searchAddress', {
              params: {
                keyword: queryString.trim(),
                cityCode: this.form.cityCode
              }
            });
            
            if (response.data.success) {
              // 转换数据格式以适配前端显示（为el-autocomplete组件增加value字段）
              const addresses = (response.data.data || []).map(item => ({
                value: item.title, // el-autocomplete组件需要的value字段
                title: item.title,
                address: item.address,
                latitude: item.latitude,
                longitude: item.longitude,
                cityCode: item.cityCode,
                province: item.province,
                city: item.city,
                district: item.district
              }));
              callback(addresses);
            } else {
              console.error('地址搜索失败:', response.data.msg);
              callback([]);
            }
          } catch (error) {
            console.error('地址搜索请求失败:', error);
            callback([]);
          }
        },
            // 取消操作
            cancelOperation() {
                this.isAdding = false;
                this.isEditing = false;
                this.resetForm();
            },

            // 重置表单
            resetForm() {
                this.form = {
                    id: null,
                    name: '',
                    address: '',
                    region: [],
                    cityCode: null,
                    addressKeyword: '',
                    selectedAddress: null,
                    spt: '',
                    pushSwitch: false
                };

                if (this.$refs.form) {
                    this.$refs.form.resetFields();
                }
            },

            // 处理地区选择变化
            handleRegionChange(values) {
                if (values && values.length > 0) {
                    this.form.cityCode = parseInt(values[values.length - 1]);
                } else {
                    this.form.cityCode = null;
                    this.form.selectedAddress = null;
                    this.form.addressKeyword = '';
                }
            },

            // 处理地址选择
            handleAddressSelect(item) {
                this.form.selectedAddress = item;
            },

            // 提交新增表单
            async submitForm() {
                this.$refs.form.validate(async (valid) => {
                    if (valid) {
                        // 准备提交的数据
                        const submitData = {
                            name: this.form.selectedAddress.title,
                            address: this.form.selectedAddress.address,
                            cityCode: this.form.cityCode,
                            latitude: this.form.selectedAddress.latitude,
                            longitude: this.form.selectedAddress.longitude,
                            spt: this.form.spt || null,
                            pushSwitch: this.form.pushSwitch
                        };

                        this.loading = true;
                        try {
                            const response = await axios.post('/api/location', submitData);
                            if (response.data.success) {
                                this.$message.success('地址新增成功');
                                // 重新加载地址列表
                                await this.loadAddressList();
                                // 重置状态
                                this.isAdding = false;
                                this.resetForm();
                            } else {
                                this.$message.error(response.data.msg || '地址新增失败');
                            }
                        } catch (error) {
                            console.error('新增地址失败:', error);
                            this.$message.error('新增地址失败，请检查网络连接');
                        } finally {
                            this.loading = false;
                        }
                    }
                });
            },

            // 提交更新表单
            async updateForm() {
                // 准备更新的数据（仅包含可编辑的字段）
                const updateData = {
                    spt: this.form.spt || null,
                    pushSwitch: this.form.pushSwitch
                };

                this.loading = true;
                try {
                    const response = await axios.put(`/api/location/${this.form.id}`, updateData);
                    if (response.data.success) {
                        this.$message.success('地址更新成功');
                        // 重新加载地址列表
                        await this.loadAddressList();
                        // 重置状态
                        this.isEditing = false;
                        this.resetForm();
                    } else {
                        this.$message.error(response.data.msg || '地址更新失败');
                    }
                } catch (error) {
                    console.error('更新地址失败:', error);
                    this.$message.error('更新地址失败，请检查网络连接');
                } finally {
                    this.loading = false;
                }
            },

            // 删除地址
            deleteAddress(id, index) {
                this.$confirm('确定要删除这个地址吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    this.loading = true;
                    try {
                        const response = await axios.delete(`/api/location/${id}`);
                        if (response.data.success) {
                            this.$message.success('地址删除成功');
                            // 重新加载地址列表
                            await this.loadAddressList();
                        } else {
                            this.$message.error(response.data.msg || '地址删除失败');
                        }
                    } catch (error) {
                        console.error('删除地址失败:', error);
                        this.$message.error('删除地址失败，请检查网络连接');
                    } finally {
                        this.loading = false;
                    }
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            }
        }
    });
</script>
</body>
</html>
